package expiring;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.HashMap;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class Alexa extends Thread{
	String domain = "";
	HashMap<String,String> alexaDomain = new HashMap<String,String>();
	public Alexa(String domain,HashMap<String, String> alexaDomain)
	{
		this.domain = domain;
		this.alexaDomain = alexaDomain;
		this.start();
	}
	
	public void run()
	{
		try {
			alexaDomain.put(domain, "0");
			String content = "";
			URL dataURL = new URL("http://xml.alexa.com/data?cli=10&dat=nsa&url="+domain);
			HttpURLConnection connection = (HttpURLConnection) dataURL.openConnection();
			connection.setReadTimeout(500000);
			connection.setConnectTimeout(1000000);
			connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.21) Gecko/20110830 AlexaToolbar/alxf-2.14 AlexaToolbar/pXVUnvuf-1.2 Firefox/3.6.21");
			connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
			connection.setRequestProperty("Accept-Charset", "	ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			connection.setRequestProperty("Connection", "keep-alive");
			connection.setRequestProperty("Keep-Alive", "115");
			connection.setRequestProperty("Cache-Control", "max-age=0");
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF8")));
			while(1==1)
			{
				String str = reader.readLine();
				if(str==null) break;
				content+=str;
				
			}
			
			Document doc = Jsoup.parse(content);
			String alexa = "-";
			
			if(!doc.select("popularity").attr("text").equals(""))
			{
				alexa = doc.select("popularity").attr("text");
			}

			alexaDomain.put(domain, alexa);
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
}
